package com.wanshi.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.wanshi.po.Result;
import com.wanshi.po.User;
import com.wanshi.utils.Constants;
import org.springframework.util.StringUtils;

@WebFilter(urlPatterns = {"/*"})
public class RoleFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
				
        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getContextPath();//   /daiti
        String uri = req.getRequestURI().substring(path.length());

        if (uri.startsWith("/dati")) {
            User user = (User) req.getSession().getAttribute("user");
            if(user == null){
                String header = req.getHeader("X-Requested-With");
                if(!StringUtils.isEmpty(header) && "XMLHttpRequest".equals(header)){
                    //ajax请求
                    response.getWriter().write(JSON.toJSONString(new Result(Constants.NO_LOGIN)));
                } else{
                    HttpServletResponse resp = (HttpServletResponse) response;
                    resp.sendRedirect(path+"/login.jsp?error="+ URLEncoder.encode("登录过期,请重新登录","utf-8"));
                }
                return;
            }
        }
        chain.doFilter(request,response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

}
